import {
  getConfig,
  userCollection
} from '../utils/config'
import {
  createToken
} from '../utils/uni-token'

import getValidInviteCode from './get-valid-Invite-code'

async function addUser (user, options = {}) {
  const addRes = await userCollection.add({
    ...user,
    register_date: Date.now(),
    register_ip: __ctx__.CLIENTIP
  })

  const uid = addRes.id

  const {
    token,
    tokenExpired
  } = createToken({
    uid,
    needPermission: options.needPermission
  })

  await userCollection.doc(uid).update({
    token: [token]
  })

  return {
    token,
    tokenExpired,
    uid,
    type: 'register'
  }
}

export default async function (user, options = {}) {
  let registerResult
  const {
    my_invite_code: inviteCode
  } = user
  const config = getConfig()
  if (!config.autoSetInviteCode && !inviteCode) {
    registerResult = await addUser(user, options)
    return {
      code: 0,
      msg: '注册成功',
      ...registerResult
    }
  }
  const validResult = await getValidInviteCode({
    inviteCode
  })
  if (validResult.code > 0) {
    return validResult
  }
  user.my_invite_code = validResult.inviteCode
  registerResult = await addUser(user, options)
  return {
    code: 0,
    msg: '注册成功',
    ...registerResult
  }
}
